def apply_diff(d, x1, y1, x2, y2, c):
    """ 更新差分矩阵（0-based坐标） """
    d[x1 + 1][y1 + 1] += c
    d[x1 + 1][y2 + 2] -= c
    d[x2 + 2][y1 + 1] -= c
    d[x2 + 2][y2 + 2] += c


def compute_final_matrix(n, m, updates):
    """ 输入矩阵尺寸和更新操作，返回最终矩阵 """
    # 初始化差分矩阵 (n+2)x(m+2)
    d = [[0] * (m + 2) for _ in range(n + 2)]

    # 应用所有更新
    for x1, y1, x2, y2, c in updates:
        apply_diff(d, x1, y1, x2, y2, c)

    # 计算二维前缀和
    matrix = [[0] * m for _ in range(n)]
    for i in range(n):
        row_prefix = 0
        for j in range(m):
            # 累加左上方的所有影响
            current = d[i + 1][j + 1]
            if i > 0:
                current += matrix[i - 1][j]
            if j > 0:
                current += row_prefix
                if i > 0:
                    current -= matrix[i - 1][j - 1]
            matrix[i][j] = current
            row_prefix = current if j == 0 else row_prefix + d[i + 1][j + 1]
    return matrix


# 示例使用
if __name__ == "__main__":
    # 案例：3x3零矩阵，对子矩阵(0,0)-(1,1)加5（0-based）
    n, m = 3, 3
    updates = [(0, 0, 1, 1, 5)]

    # 计算结果矩阵
    result = compute_final_matrix(n, m, updates)

    # 打印结果
    print("更新后的矩阵：")
    for row in result:
        print(row)
